﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Transactions;


public class WithdrawMoney
{
    private const string CONNECTION_STRING = "Data Source=.\\SQLEXPRESS;Initial Catalog=ATM;Integrated Security=True";

    static public void Withdraw(string cardNum, string pin, decimal ammount)
    {
        SqlConnection dbCon = new SqlConnection(CONNECTION_STRING);
        try
        {
            using (TransactionScope scope = new TransactionScope())
            {
                dbCon.Open();
                try
                {
                    Console.WriteLine("Transaction started.");

                    SqlCommand cmd = dbCon.CreateCommand();
                    cmd.CommandText =
                        "Select CardCash from CardAccounts where CardNumber = @cardNum and CardPIN = @PIN";
                    cmd.Parameters.Add("@cardNum", cardNum);
                    cmd.Parameters.Add("@PIN", pin);
                    decimal? cash = (decimal)cmd.ExecuteScalar();
                    
                    
                    if (cash > ammount)
                    {
                        //Console.WriteLine("{0} paid to the person :)", cash);
                        UpdateDB(dbCon, ammount, cardNum);
                        Console.WriteLine("Completed successfully.");
                        scope.Complete();
                    }
                    else
                    {
                        Console.WriteLine("Not enough money to get.");
                    }
                     
                     
                }
                catch (SqlException e)
                {
                    Console.WriteLine("Exception occured: {0}", e.Message);
                    Console.WriteLine("Money withdraw cancelled.");
                }
            }

        }
        finally
        {
            dbCon.Close();
        }
    }

    private static void UpdateDB(SqlConnection dbCon, decimal? ammount, string cardNum)
    {
        using (TransactionScope scope =
                new TransactionScope(TransactionScopeOption.Required))
        {
            SqlCommand cmnd = dbCon.CreateCommand();

            cmnd.CommandText =
            "Update CardAccounts set CardCash = CardCash - @ammount where CardNumber = @cardNum";
            cmnd.Parameters.Add("@ammount", ammount);
            cmnd.Parameters.Add("@cardNum", cardNum);
            cmnd.ExecuteNonQuery();
            scope.Complete();
        }
    }

    static void Main()
    {
        Withdraw("Filip", "1234", 3000);
    }
}